﻿using Microsoft.AspNetCore.Mvc;
using ZingBlog.Domain.Entities;
using ZingBlog.IService;
using ZingBlog.Web.Models;


namespace ZingBlog.Web.Controllers
{
    public class QQUserController : Controller
    {
        public IQQUserService service { get; set; }
        // GET: QQUser
        public ActionResult QQLogin()
        {
            string state = DateTime.Now.ToString("yyyyMMddHHmmssffff");  //client端的状态值。用于第三方应用防止CSRF攻击，成功授权后回调时会原样带回。
            string url = QQLoginHelper.CreateAuthorizeUrl(state);
            HttpContext.Session.SetString("QQLoginState", state);  //记录client端状态值
            HttpContext.Session.SetString("BeforeLoginUrl", Request.Headers["Referer"].ToString());    //记录登陆之前的URL，登陆成功后返回                                                              
            return Redirect(url);
        }
        public ActionResult QQLoginTest()
        {
            string state = DateTime.Now.ToString("yyyyMMddHHmmssffff");  //client端的状态值。用于第三方应用防止CSRF攻击，成功授权后回调时会原样带回。
            HttpContext.Session.SetString("QQLoginState", state);  //记录client端状态值   //记录登陆之前的URL，登陆成功后返回                                                              
            return Content(HttpContext.Session.GetString("QQLoginState"));
        }
        public ActionResult CallBack()
        {
            string backState = Request.Query["state"];
            string code = Request.Query["code"];
            var qqLoginState = HttpContext.Session.GetString("QQLoginState");
            if (null != backState && null != code && null != qqLoginState && backState == qqLoginState)
            {
                HttpContext.Session.Remove("QQLoginState");
                //调获取AccessToken的接口
                string access_token = QQLoginHelper.GetAccessToken(code);
                //调获取OpenID的接口
                string openid = QQLoginHelper.GetOpenId(access_token);
                //调获取用户信息的接口
                QQUserInfo qqUserInfo = QQLoginHelper.GetQQUserInfo(access_token, openid);
                if (qqUserInfo.ret == 0 && string.IsNullOrEmpty(qqUserInfo.msg))
                {
                    var userModel = service.GetByWhere("WHERE OpenId='" + openid + "'").FirstOrDefault();
                    if (userModel != null)
                    {
                        //更新QQ用户信息
                        userModel.NickName = qqUserInfo.nickname;
                        userModel.Gender = qqUserInfo.gender == "男" ? 1 : 0;
                        userModel.HeadShot = qqUserInfo.figureurl_qq;
                        userModel.LastLogin = DateTime.Now;
                        service.UpdateEntity(userModel);
                    }
                    else
                    {
                        userModel = new QQUserEntity();
                        //添加QQ用户
                        userModel.OpenId = openid;
                        userModel.NickName = qqUserInfo.nickname;
                        userModel.Gender = qqUserInfo.gender=="男"?1:0;
                        userModel.HeadShot = qqUserInfo.figureurl_qq;
                        userModel.Email = "";
                        userModel.Status = true;
                        userModel.LastLogin = DateTime.Now;
                        userModel.CreateOn = DateTime.Now;
                        service.CreateEntity(userModel);
                    }
                    Response.Cookies.Append("openid", openid,new CookieOptions() { Expires = DateTime.Now.AddDays(3) });
                    Response.Cookies.Append("nickname", qqUserInfo.nickname, new CookieOptions() { Expires = DateTime.Now.AddDays(3) });
                    Response.Cookies.Append("figureurl_qq", qqUserInfo.figureurl_qq, new CookieOptions() { Expires = DateTime.Now.AddDays(3) });
                }
                else
                {
                    //获取用户失败
                    throw new ApplicationException(qqUserInfo.msg);
                }
                if (HttpContext.Session.GetString("BeforeLoginUrl") != null)
                {
                    return Redirect(HttpContext.Session.GetString("BeforeLoginUrl").ToString()); //返回登陆之前的URL
                }
                else
                {
                    throw new Exception("登录之前的路由丢失");
                }
            }
            else
            {
                return Content($"sessionstate:{HttpContext.Session.GetString("QQLoginState")}");
            }
        }
        public ActionResult QQLogOut()
        {
            Response.Cookies.Append("openid", null, new CookieOptions() { Expires = DateTime.Now.AddDays(-1) });
            Response.Cookies.Append("nickname", null, new CookieOptions() { Expires = DateTime.Now.AddDays(-1) });
            Response.Cookies.Append("figureurl_qq", null, new CookieOptions() { Expires = DateTime.Now.AddDays(-1) });
            return Redirect(Request.Headers["Referrer"].ToString());
        }
    }
}